package com.net.xpay.sync.client;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.google.common.base.Preconditions;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;


@Data
public class CanalSyncContext {
    private CanalEntry.RowData rowData;

    private String beforeBeanJson;

    private String afterBeanJson;
    //数据库名
    private String schemaName;
    //表名
    private String tableName;
    //主键
    private String id;

    //主键名字 固定为id
    private static final String PRIMARY_KEY_NAME = "id";

    public static CanalSyncContext getInstance(CanalEntry.Entry entry, CanalEntry.RowData rowData) {
        CanalSyncContext canalSyncContext = new CanalSyncContext();
        canalSyncContext.setSchemaName(entry.getHeader().getSchemaName());
        canalSyncContext.setTableName(entry.getHeader().getTableName());
        canalSyncContext.setBeforeBeanJson(CanalBeanHelper.convertToBeanJson(rowData.getBeforeColumnsList()));
        canalSyncContext.setAfterBeanJson(CanalBeanHelper.convertToBeanJson(rowData.getAfterColumnsList()));
        canalSyncContext.setRowData(rowData);
        canalSyncContext.setId(resolveIdFromRowData(rowData));
        //主键为空 这是不允许的 没法跟新没法删除没法插入
        Preconditions.checkArgument(canalSyncContext.getId() != null);
        return canalSyncContext;
    }

    //解析出主键id
    private static String resolveIdFromRowData(CanalEntry.RowData rowData) {
        String id = resolveIdFromColumns(rowData.getBeforeColumnsList());
        if (id != null) {
            return id;
        }

        return resolveIdFromColumns(rowData.getAfterColumnsList());

    }

    private static String resolveIdFromColumns(List<CanalEntry.Column> columnsList) {
        if (CollectionUtils.isEmpty(columnsList)) {
            return null;
        }

        for (CanalEntry.Column column : columnsList) {
            if (PRIMARY_KEY_NAME.equals(column.getName())) {
                return column.getValue();
            }
        }
        return null;
    }
}
